﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;

namespace Project_1
{
    /// <summary>
    /// 1.12 线程的异常处理
    /// </summary>
    public class Unit_1_12
    {
        public static void Go()
        {
            //在线程中处理异常，正确做法
            var t = new Thread(FaultyThread);
            //t.Start();
            //t.Join();

            //在线程外捕捉异常，错误做法，线程外捕捉不到线程抛出的异常！！
            try
            {
                t = new Thread(BadFaultyThread);
                t.Start();
            }
            catch (AggregateException ae)
            {
                var list = ae.Message;
            }
            catch (Exception e)
            {
                WriteLine("不会执行到这里");
            }
        }

        //不进行异常处理
        static void BadFaultyThread()
        {
            WriteLine("启动一个错误线程...");
            Sleep(TimeSpan.FromSeconds(2));
            throw new Exception("异常");
        }

        //进行线程的异常处理
        static void FaultyThread()
        {
            try
            {
                WriteLine("启动一个错误线程...");
                Sleep(TimeSpan.FromSeconds(1));
                throw new Exception("异常");
            }
            catch (Exception e)
            {
                WriteLine($"错误处理：{e.Message}");
            }
        }
    }
}
